package net.pessu.android.shoppoid.wishlist;

import greendroid.app.GDActivity;
import greendroid.widget.ActionBar;
import greendroid.widget.ActionBarItem;
import greendroid.widget.NormalActionBarItem;

import java.util.Date;

import net.pessu.android.shoppoid.R;
import net.pessu.android.shoppoid.bean.Article;
import net.pessu.android.shoppoid.gui.ButtonListLayout;
import net.pessu.android.shoppoid.gui.ButtonListRemise;
import net.pessu.android.shoppoid.gui.IhmObjets;
import net.pessu.android.shoppoid.gui.TextSolution;
import net.pessu.android.shoppoid.util.ConstanteArticles;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;

public class AddArticle extends GDActivity {

	private static final String TAG = "AddArticle";

	private static final String UNE_ERREUR_EST_SURVENUE = IhmObjets
			.getStringContext(R.string.erreursurvenue);
	private static final String CHOISIR_UN_TYPE_D_ARTICLE = IhmObjets
			.getStringContext(R.string.choisirtypearticle);
	private static final String ARTICLE_AJOUTER = IhmObjets
			.getStringContext(R.string.articleajouter);
	private static final String ARTICLE_MODIFIER = IhmObjets
			.getStringContext(R.string.articlemodifier);
	private static final String ARTICLE2 = IhmObjets
			.getStringContext(R.string.article);;
	private static final String STRING = "";

	int id = -1;
	TextView nom;
	TextView desc;
	TextSolution prix;
	TextSolution prixOrigine;
	TextView type;
	boolean fromRemise = false;
	Context currentContext;
	ButtonListLayout buttonListLayout;
	CheckBox checkBoxAcheter;

	WishListService service;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setActionBarContentView(R.layout.addarticleform);
		ActionBar bar = getActionBar();
		bar.setTitle(getString(R.string.liste));
		bar.setFont(IhmObjets.tfTitre);
		bar.setFontSize(30);
		addActionBarItem(
				getActionBar().newActionBarItem(NormalActionBarItem.class)
						.setDrawable(R.drawable.save)
						.setContentDescription(R.string.save_article),
				R.id.action_bar_save_article);

		Bundle b = getIntent().getExtras();

		service = WishListService.getInstance(this);
		currentContext = this;

		nom = (TextView) findViewById(R.id.nomArticle);
		desc = (TextView) findViewById(R.id.descArticle);
		prix = (TextSolution) findViewById(R.id.prixArticle);
		prixOrigine = (TextSolution) findViewById(R.id.prixOrigine);
		type = (TextView) findViewById(R.id.catArticle);
		
		checkBoxAcheter = (CheckBox) findViewById(R.id.checkBoxAcheter);
		
		buttonListLayout = (ButtonListLayout) findViewById(R.id.ButtonListRemiseLayout);

		((ButtonListRemise) findViewById(R.id.cinq)).init(0.95, prixOrigine,
				prix, buttonListLayout);
		((ButtonListRemise) findViewById(R.id.dix)).init(0.90, prixOrigine,
				prix, buttonListLayout);
		((ButtonListRemise) findViewById(R.id.quinze)).init(0.85, prixOrigine,
				prix, buttonListLayout);
		((ButtonListRemise) findViewById(R.id.vingt)).init(0.80, prixOrigine,
				prix, buttonListLayout);
		((ButtonListRemise) findViewById(R.id.vingtcinq)).init(0.75,
				prixOrigine, prix, buttonListLayout);
		((ButtonListRemise) findViewById(R.id.trente)).init(0.70, prixOrigine,
				prix, buttonListLayout);
		((ButtonListRemise) findViewById(R.id.trentecinq)).init(0.65,
				prixOrigine, prix, buttonListLayout);
		((ButtonListRemise) findViewById(R.id.quarante)).init(0.60,
				prixOrigine, prix, buttonListLayout);
		((ButtonListRemise) findViewById(R.id.quarantecinq)).init(0.55,
				prixOrigine, prix, buttonListLayout);
		((ButtonListRemise) findViewById(R.id.cinquante)).init(0.50,
				prixOrigine, prix, buttonListLayout);
		((ButtonListRemise) findViewById(R.id.cinquantecinq)).init(0.45,
				prixOrigine, prix, buttonListLayout);
		((ButtonListRemise) findViewById(R.id.soixante)).init(0.40,
				prixOrigine, prix, buttonListLayout);
		((ButtonListRemise) findViewById(R.id.soixantecinq)).init(0.35,
				prixOrigine, prix, buttonListLayout);
		((ButtonListRemise) findViewById(R.id.soixantedix)).init(0.30,
				prixOrigine, prix, buttonListLayout);
		((ButtonListRemise) findViewById(R.id.soixantequinze)).init(0.25,
				prixOrigine, prix, buttonListLayout);
		((ButtonListRemise) findViewById(R.id.quatrevingt)).init(0.20,
				prixOrigine, prix, buttonListLayout);
		((ButtonListRemise) findViewById(R.id.quatrevingtcinq)).init(0.15,
				prixOrigine, prix, buttonListLayout);
		((ButtonListRemise) findViewById(R.id.quatrevingtdix)).init(0.10,
				prixOrigine, prix, buttonListLayout);
		((ButtonListRemise) findViewById(R.id.quatrevingtquinze)).init(0.05,
				prixOrigine, prix, buttonListLayout);

		if (b != null && b.containsKey(ARTICLE2)) {
			Article article = (Article) b.getSerializable(ARTICLE2);
			if (article.getPrixreduit() > 0) {
				prix.setText(IhmObjets.df.format(article.getPrixreduit()));
			} else {
				prix.setText(IhmObjets.df.format(getPrixFinal(
						article.getPrixreduit(), article.getTauxReduc())));
			}
			if (article.getPrixOrigine() > 0) {
				prixOrigine.setText(IhmObjets.df.format(article
						.getPrixOrigine()));
			} else {
				prixOrigine.setText(IhmObjets.df.format(getPrixOrigine(
						article.getPrixreduit(), article.getTauxReduc())));
			}
			buttonListLayout.selectButton(article.getTauxReduc());

			if (article.getTitre() != null
					&& !article.getTitre().equals(STRING)) {
				nom.setText(article.getTitre());
				desc.setText(article.getDescription());
				type.setText(article.getTypeAchat());
				id = article.getId();
			} else {
				fromRemise = true;
			}
			
			checkBoxAcheter.setChecked(article.isAcheter());
		}

		type.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				AlertDialog.Builder builder = new AlertDialog.Builder(
						currentContext);
				builder.setTitle(CHOISIR_UN_TYPE_D_ARTICLE);
				builder.setSingleChoiceItems(ConstanteArticles.items, -1,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int item) {
								Toast.makeText(getApplicationContext(),
										ConstanteArticles.items[item],
										Toast.LENGTH_SHORT).show();
								type.setText(ConstanteArticles.items[item]);
								dialog.cancel();
							}
						});
				AlertDialog alert = builder.create();
				alert.show();
			}
		});

		prix.setOnFocusChangeListener(new OnFocusChangeListener() {

			public void onFocusChange(View v, boolean hasFocus) {
				double prixFinal = 0;

				try {
					prixFinal = Double.parseDouble(prix.getText().toString());
				} catch (NumberFormatException nfe) {
					Log.e(TAG, nfe.toString());
				}
				if (prixFinal > 0) {
					prixOrigine.setText(IhmObjets.df.format(getPrixOrigine(
							prixFinal, getTauxAppliquer())));
				}

			}
		});

		prixOrigine.setOnFocusChangeListener(new OnFocusChangeListener() {

			public void onFocusChange(View v, boolean hasFocus) {
				double prixSansReduc = 0;

				try {
					prixSansReduc = Double
							.parseDouble(AddArticle.this.prixOrigine.getText()
									.toString());
				} catch (NumberFormatException nfe) {
					Log.e(TAG, nfe.toString());
				}
				if (prixSansReduc > 0) {
					prix.setText(IhmObjets.df.format(getPrixFinal(
							prixSansReduc, getTauxAppliquer())));
				}

			}
		});

	}

	private double getTauxAppliquer() {
		return buttonListLayout.getSelectedButtonTaux();
	}

	protected void photoAdder() {
		Intent i = new Intent(this, PhotoArticle.class);
		startActivity(i);
	}

	@Override
	public boolean onHandleActionBarItemClick(ActionBarItem item, int position) {

		switch (item.getItemId()) {
		case R.id.action_bar_save_article:
			if (nom.getText() != null
					&& nom.getText().toString().trim().length() > 0) {
				Article article = new Article();
				if (id >= 0) {
					article.setId(id);
				}
				article.setTitre(nom.getText().toString());
				article.setDescription(desc.getText().toString());
				if (prix.getText().toString() != null
						&& prix.getText().toString() != STRING
						&& prix.getText().toString().trim().length() != 0) {
					article.setPrixreduit(Double.parseDouble(prix.getText()
							.toString().replace(",", ".")));
				} else {
					article.setPrixreduit(0.0);
				}
				if (prixOrigine.getText().toString() != null
						&& prixOrigine.getText().toString() != STRING
						&& prixOrigine.getText().toString().trim().length() != 0) {
					article.setPrixOrigine(Double.parseDouble(prixOrigine
							.getText().toString().replace(",", ".")));
				} else {
					article.setPrixOrigine(0.0);
				}
				article.setTypeAchat(type.getText().toString());
				article.setTauxReduc(getTauxAppliquer());
				article.setDate(new Date());
				article.setAcheter(checkBoxAcheter.isChecked());
				boolean ok = false;
				if (id >= 0) {
					ok = service.editArticle(article);
					Toast.makeText(getApplicationContext(), ARTICLE_MODIFIER,
							Toast.LENGTH_SHORT).show();
				} else {
					ok = service.addArticle(article);
					Toast.makeText(getApplicationContext(), ARTICLE_AJOUTER,
							Toast.LENGTH_SHORT).show();
				}
				if (ok) {
					if (IhmObjets.listeArticles != null) {
						IhmObjets.listeArticles.refreshAdaptater(service
								.getListArticles());
					} else {
						IhmObjets.isListToRefresh = true;
					}

					finish();
					if (fromRemise) {
						wishListAdder();
					}
				} else {
					IhmObjets.ajouterBoiteDeDialogue(currentContext,
							UNE_ERREUR_EST_SURVENUE);
				}
			} else {
				Toast.makeText(getApplicationContext(),
						IhmObjets.getStringContext(R.string.erreuraddarticle),
						Toast.LENGTH_SHORT);
			}

			break;

		default:
			return super.onHandleActionBarItemClick(item, position);
		}

		return true;
	}

	/**
	 * Calcul le prix original a partir du prix final et du taux
	 * 
	 * @param prixFinal
	 * @param taux
	 * @return
	 */
	private double getPrixOrigine(double prixFinal, double taux) {
		return (taux > 0) ? (prixFinal / taux) : prixFinal;
	}

	/**
	 * Calcul le prix final en fonction du prix d'origine et du taux
	 * 
	 * @param prixFinal
	 * @param taux
	 * @return
	 */
	private double getPrixFinal(double prixFinal, double taux) {
		return taux > 0 ? (prixFinal * taux) : prixFinal;
	}

	/**
	 * Launches the wishlist activity to add a new contact to the selected
	 * accont.
	 */
	protected void wishListAdder() {
		startActivity(new Intent(this, WishList.class));
	}
}
